package com.example.framework.config.RestTemplate;
import com.example.framework.common.exception.RestTemplateResponseErrorHandler;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.security.oauth2.core.http.converter.OAuth2AccessTokenResponseHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.annotation.RequestScope;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;

@Configuration
public class RestTemplateConfig {
    private final ObjectMapper objectMapper;

    public RestTemplateConfig(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Bean
    @RequestScope
    public RestTemplate restTemplate(ClientHttpRequestFactory factory,HttpServletRequest inReq, RestTemplateBuilder restTemplateBuilder) {
        final RestTemplate restTemplate = new RestTemplate(factory);
        // 构建restTemplate，请注册异常处理
        restTemplate.setErrorHandler(new RestTemplateResponseErrorHandler(objectMapper));
        // 检查是否有oauth2的认证标识，有就需要传递在header中
        final String authHeader = inReq.getHeader(HttpHeaders.AUTHORIZATION);
        final String mindrayCustomKey = inReq.getHeader("MINDRAY-CUSTOM-KEY");
        System.out.println("restTemplate request token:"+authHeader);
        System.out.println("restTemplate request MINDRAY-CUSTOM-KEY :"+mindrayCustomKey);
        if (authHeader != null && !authHeader.isEmpty()) {
            restTemplate.getInterceptors().add(
                    (outReq, bytes, clientHttpReqExec) -> {
                        outReq.getHeaders().set(
                                HttpHeaders.AUTHORIZATION, authHeader
                        );
                        return clientHttpReqExec.execute(outReq, bytes);
                    });
        }
        OAuth2AccessTokenResponseHttpMessageConverter oac = new OAuth2AccessTokenResponseHttpMessageConverter();
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        return restTemplate;
    }

    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
        SSL factory = new SSL();
        factory.setReadTimeout(60*1000);
        factory.setConnectTimeout(60*1000);
        return factory;
    }
}
